package cn.chencaiju.blog.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.chencaiju.blog.domain.AjaxResponse;
import cn.chencaiju.blog.domain.Category;
import cn.chencaiju.blog.service.CategoryService;
import cn.chencaiju.blog.utils.ServiceProxyUtils;


@WebServlet(
		urlPatterns= {"/category/page","/category/delete","/category/update"}
		)
public class CategoryServlet extends BaseServlet {
	CategoryService service = ServiceProxyUtils.createProxy(new CategoryService());
	
	public void page(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		String pages = req.getParameter("page");
		String limit = req.getParameter("limit");
		AjaxResponse<Category> response = service.page(pages,limit);
		if(response!=null) {
			String jsonString = JSON.toJSONString(response);
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().write(jsonString);
		}		
		
	}

	public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int id = Integer.valueOf(req.getParameter("id"));
		
		// 返回一个简单的响应消息
		AjaxResponse<Category> response = new AjaxResponse<>();
		try {
			service.delete(id);
			response.setCode(0);
			response.setMsg("success");
		} catch (Exception e) {
			System.out.println(e);
			
			response.setCode(1);
			response.setMsg("数据库操作失败！");
		}
		
		String string = JSON.toJSONString(response);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);
	}
	public void update(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
		System.out.println("update....");
		int id=Integer.valueOf(req.getParameter("id"));
		System.out.println(id);
		String name = req.getParameter("name");
		System.out.println(name);
		Category cate=new Category();
		cate.setId(id);
		cate.setName(name);
//		cate.setPriority(priority);
		
//		AjaxResponse<Category> response = new AjaxResponse<>();
		service.update(cate);
	}
}
